<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    width="60%"
    v-dialog-drag
    :close-on-click-modal="false"
    top="5vh"
    @close="handleClose()"
    @open="handleOpen()"
  >
    <PartitionTitle title="基础信息"></PartitionTitle>
    <el-form
      :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      :disabled="!canEdit"
    >
      <el-form-item label="产线编码" prop="erpProductionLineCode">
        <el-input
          type="text"
          v-model="form.erpProductionLineCode"
          placeholder="请输入产线编码"
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item label="产线名称" prop="erpProductionLineName">
        <el-input
          type="text"
          v-model="form.erpProductionLineName"
          placeholder="请输入产线名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="所属工厂" prop="factoryDeptName">
        <el-input
          type="text"
          v-model="form.factoryDeptName"
          placeholder="请输入所属工厂"
          disabled
        ></el-input>
      </el-form-item>
      <el-form-item label="所属车间" prop="workshopCode">
        <el-select
          v-model="form.workshopCode"
          placeholder="请选择所属车间"
          size="small"
          @change="handleWorkshopCodeChange"
        >
          <el-option
            v-for="item in workshopOptions"
            :key="item.workshopCode"
            :label="item.workshopName"
            :value="item.workshopCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="isBlowIrriagtionSpin"
        label="产线类型"
        prop="lineType"
      >
        <el-select
          v-model="form.lineType"
          placeholder="请选择产线类型"
          size="small"
          @change="handleLineTypeChange"
        >
          <el-option
            v-for="item in lineTypeOptions"
            :key="item.codevalue"
            :label="item.codename"
            :value="item.codevalue"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="isBlowIrriagtionSpin"
        label="产线品类"
        prop="lineCategory"
      >
        <el-select
          v-model="form.lineCategory"
          placeholder="请选择产线品类"
          size="small"
        >
          <el-option
            v-for="item in lineCategoryOptions"
            :key="item.codevalue"
            :label="item.codename"
            :value="item.codevalue"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template v-if="isBlowIrriagtionSpin">
      <PartitionTitle title="月标准天数"></PartitionTitle>
      <div class="table-form">
        <FormTemplate
          ref="tableForm"
          :templateConfig="monthTableConfig"
          :formData="form"
          :disabled="!canEdit"
        ></FormTemplate>
        <div class="error-tip el-form-item__error">{{ monthError }}</div>
      </div>
      <!-- <div class="standard-search">
        <el-select
          v-model="standardSearch"
          placeholder="请选择月份"
          size="small"
          clearable
        >
          <el-option
            v-for="item in monthOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-button type="primary" size="small" @click="getStandardTableData"
          >查询</el-button
        >
      </div>
      <el-table
        :data="standardTable"
        border
        :resizable="false"
        style="width: 100%"
        v-loading="standardLoading"
      >
        <el-table-column prop="erpItemCapacity" label="产品容量">
        </el-table-column>
        <el-table-column prop="erpRatedLineSpeed" label="额定线速">
        </el-table-column>
        <el-table-column prop="erpMechanEfficiencyCoef" label="标准效率">
        </el-table-column>
        <el-table-column prop="standardWorkHours" label="标准工时">
        </el-table-column>
        <el-table-column prop="standardBoxedNums" label="单箱瓶数">
        </el-table-column>
        <el-table-column prop="monthWorkdays" label="月天数"> </el-table-column>
        <el-table-column prop="ratedProduction" label="月标准产能">
        </el-table-column>
      </el-table> -->
    </template>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button
        v-if="canEdit"
        type="primary"
        :loading="saveloading"
        @click="handleSubmit"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import {
  getErpProductionLine,
  addOrUpdateErpProductionLine,
  getListLineCapacity,
} from "@/api/prodLineMgmt/productionLine";
import { listWorkshop } from "@/api/prodLineMgmt/workshop";
import FormTemplate from "@/views/components/formTemplate";
import { checkPermi } from "@/utils/permission";
import { getDicts } from "@/api/system/crccode";
export default {
  components: { FormTemplate },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  dicts: ["produceLineType"],
  data() {
    return {
      form: {
        id: null,
        factoryDeptCode: null,
        factoryDeptName: null,
        erpProductionLineCode: null,
        erpProductionLineName: null,
        lineType: null,
        lineCategory: null,
        workshopCode: null,
        workshopType: null,
        lineWorkdaysDtos: [],
      },
      lineCategoryOptions: [],
      workshopOptions: [],
      rules: {
        erpProductionLineName: [
          { required: true, message: "请输入产线名称", trigger: "change" },
        ],
        lineType: [
          { required: true, message: "请选择产线类型", trigger: "change" },
        ],
        lineCategory: [
          { required: true, message: "请选择产线品类", trigger: "change" },
        ],
        workshopCode: [
          { required: true, message: "请选择所属车间", trigger: "change" },
        ],
      },
      monthTableConfig: {
        totalCol: 13,
        title: "",
        config: [
          {
            id: "row_1",
            cells: [],
          },
          {
            id: "row_2",
            cells: [],
          },
        ],
      },
      monthError: "",
      standardSearch: "",
      monthOptions: [],
      standardTable: [],
      standardLoading: false,
      saveloading: false,
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    title() {
      if (this.disabled == true) {
        return "产线详情";
      }
      if (!!this.row) {
        return "编辑产线";
      }
      return "新增产线";
    },
    canEdit() {
      if (this.disabled == true) {
        return false;
      }
      if (this.row?.id) {
        return checkPermi(["prodLineMgmt:erpProductionLine:edit"]);
      }
      return true;
    },
    // 是否位包装车间
    isBlowIrriagtionSpin() {
      // 当选择的车间为“包装车间”时，有标准产能模块
      return this.form.workshopType == "BLOW_IRRIAGTION_SPIN";
    },
    lineTypeOptions() {
      return this.dict.produceLineType
    }
  },
  methods: {
    handleClose() {
      this.saveloading = false;
      this.resetFormData();
    },
    handleOpen() {
      this.getDetail();
    },
    // 根据产线类型获取产线品类 数据字典
    getLineCategoryOptionsByLineType(value) {
      const citem = this.lineTypeOptions.find((ele) => ele.codevalue == value);
      if (!citem?.prop1) {
        this.lineCategoryOptions = [];
        return;
      }
      getDicts(citem.prop1).then((response) => {
        this.lineCategoryOptions = response.data[citem.prop1];
      });
    },
    // 获取详情
    getDetail() {
      if (!this.row?.id) {
        return;
      }
      getErpProductionLine(this.row.id)
        .then((res) => {
          if (res.code == 200 && res.data) {
            const {
              id,
              bizDeptVo,
              erpProductionLineCode,
              erpProductionLineName,
              workshopCode,
              workshopDto,
              lineType,
              lineCategory,
              lineWorkdaysDtos,
            } = res.data;
            this.form = {
              id,
              factoryDeptCode: bizDeptVo?.deptCode,
              factoryDeptName: bizDeptVo?.deptName,
              erpProductionLineCode,
              erpProductionLineName,
              lineType,
              lineCategory,
              workshopCode,
              workshopType: workshopDto?.workshopType || null,
              lineWorkdaysDtos,
            };
            this.$nextTick(() => {
              this.$refs.ruleForm?.clearValidate();
            });
            // 根据所属工厂获取对应的车间列表
            this.getWorkShopList(bizDeptVo?.deptCode);
            // 根据产线类型获取产线类品的字典
            this.getLineCategoryOptionsByLineType(lineType);
            // 生成月天数表格模板
            this.genMonthTable(res.data.lineWorkdaysDtos);
          }
        })
        .catch(() => {});
    },
    // 生成月天数表格模板
    genMonthTable(lineWorkdaysDtos) {
      this.monthTableConfig.config[0].cells = [
        {
          id: "cell_1_1",
          content: "月份",
          controllerType: "LABEL",
          width: "50px",
          colspan: 1,
          rowspan: 1,
        },
      ];
      this.monthTableConfig.config[1].cells = [
        {
          id: "cell_2_1",
          content: "月天数",
          controllerType: "LABEL",
          width: "50px",
          colspan: 1,
          rowspan: 1,
        },
      ];
      this.monthOptions = [];
      for (let i = 0; i < lineWorkdaysDtos.length; i++) {
        const day = lineWorkdaysDtos[i];
        this.monthTableConfig.config[0].cells.push({
          id: `cell_1_${i + 2}`,
          content: day.monthStr,
          controllerType: "LABEL",
          width: "auto",
          colspan: 1,
          rowspan: 1,
        });
        this.monthTableConfig.config[1].cells.push({
          id: `cell_2_${i + 2}`,
          content: "${lineWorkdaysDtos[" + i + "].workdays}",
          controllerType: "INPUT",
          width: "auto",
          colspan: 1,
          rowspan: 1,
          required: true,
          change: (value) => {
            // 空
            if (value == null || value == undefined || value == "") {
              this.monthError = "请输入数字0~31";
              return;
            }
            // 数字
            if (/^\d+$/.test(value)) {
              if (Number(value) < 0 || Number(value) > 31) {
                this.monthError = "请输入数字0~31";
              } else {
                this.monthError = "";
              }
            } else {
              this.monthError = "请输入数字0~31";
            }
          },
        });

        this.monthOptions.push({
          value: day.monthStr,
          label: day.monthStr,
        });
      }
    },
    // 根据所属工厂获取对应的车间列表
    getWorkShopList(factoryCode) {
      const params = {
        query: {
          factoryDeptCode: factoryCode,
        },
      };
      listWorkshop(params)
        .then((response) => {
          if (response.code == 200) {
            this.workshopOptions = response.rows || [];
          } else {
            this.workshopOptions = [];
          }
        })
        .catch(() => {
          this.workshopOptions = [];
        });
    },
    // 获取标准产能数据
    getStandardTableData() {
      let workDays = 0;
      const formParam = this.$refs.tableForm.getSubmitFormData();

      const search = this.standardSearch;
      if (search) {
        // 选择的月份查询
        const item = formParam.lineWorkdaysDtos.find(
          (ele) => ele.monthStr == search
        );
        if (!item) {
          return;
        }
        workDays = item.workdays;
      } else {
        // 不选择月份，则累计所有的月份，没有维护月天数的月份，月天数默认0
        const allWorkdays = formParam.lineWorkdaysDtos.map((ele) =>
          Number(ele.workdays || 0)
        );
        workDays = allWorkdays.reduce((p, n) => {
          return p + n;
        }, 0);
      }

      this.standardLoading = true;
      const param = {
        workDays,
        factoryDeptCode: this.form.factoryDeptCode,
        lineCode: this.form.erpProductionLineCode,
      };
      getListLineCapacity(param)
        .then((res) => {
          this.standardTable = res.data || [];
          this.standardLoading = false;
        })
        .catch(() => {
          this.standardTable = [];
          this.standardLoading = false;
        });
    },
    handleLineTypeChange(value) {
      this.form.lineCategory = null;
      this.getLineCategoryOptionsByLineType(value);
    },
    handleWorkshopCodeChange(value) {
      const item = this.workshopOptions.find(
        (ele) => ele.workshopCode == value
      );
      this.form.workshopType = item?.workshopType || null;

      // 清空数据
      this.form.lineType = null;
      this.form.lineCategory = null;
    },
    updateFormData() {
      if (this.$refs.tableForm) {
        const formParam = this.$refs.tableForm.getSubmitFormData();
        this.form.lineWorkdaysDtos.forEach((ele, i) => {
          ele.workdays = formParam.lineWorkdaysDtos[i].workdays;
        });
      }
    },
    handleSubmit() {
      if (!this.canEdit) {
        return;
      }
      this.saveloading = true;
      this.$refs.ruleForm.validate((flag) => {
        if (flag && !this.monthError) {
          this.updateFormData();
          const emtyWorkdays = this.isBlowIrriagtionSpin
            ? this.form.lineWorkdaysDtos?.findIndex(
                (ele) => !ele.workdays && ele.workdays != 0
              )
            : -1;
          if (emtyWorkdays != -1) {
            this.monthError = "请输入数字0~31";
            this.saveloading = false;
            return;
          }
          const {
            id,
            erpProductionLineName,
            lineCategory,
            lineType,
            lineWorkdaysDtos,
            workshopCode,
          } = this.form;
          const param = {
            id,
            erpProductionLineName,
            lineCategory,
            lineType,
            lineWorkdaysDtos: this.isBlowIrriagtionSpin ? lineWorkdaysDtos : [],
            workshopCode,
          };
          addOrUpdateErpProductionLine(param)
            .then((res) => {
              if (res.code == 200) {
                this.msgSuccess(id ? "修改成功！" : "新增成功！");
                this.$emit("submit-success");
                this.dialogVisible = false;
              }
              this.saveloading = false;
            })
            .catch(() => {
              this.saveloading = false;
            });
        } else {
          this.saveloading = false;
        }
      });
    },
    resetFormData() {
      this.$refs.ruleForm?.resetFields();
      this.form = {
        id: null,
        factoryDeptCode: null,
        factoryDeptName: null,
        erpProductionLineCode: null,
        erpProductionLineName: null,
        lineType: null,
        lineCategory: null,
        workshopCode: null,
        workshopType: null,
        lineWorkdaysDtos: [],
      };
      if (this.$refs.tableForm) {
        this.$refs.tableForm.clearForm();
      }
      this.standardSearch = "";
      this.standardTable = [];
    },
  },
};
</script>
<style lang="scss" scoped>
.el-form {
  display: flex;
  justify-content: space-between;
  flex-flow: wrap;
  .el-form-item {
    width: 49%;
  }
  .el-date-editor.el-input,
  .el-select {
    width: 100%;
  }
}
.table-form {
  position: relative;
  .table-container {
    padding-right: 0;
  }
}
.standard-search {
  text-align: right;
  margin: 20px 0 10px;
  .el-select {
    width: 125px;
    margin-right: 10px;
  }
}
</style>
